import unittest

from psychsim.pwl import *
from psychsim.action import Action,ActionSet
from psychsim.world import World,stateKey
from psychsim.agent import Agent
from psychsim.reward import *

''' 
This example is used to test the update of beliefs on world states
according to the outcome of the last action
'''

class PoisonTestCase(unittest.TestCase):

    def setUp(self):
        #setup world, agent, and basics
        self.maxRounds=1
        self.world = World()
        self.claudius = Agent('Claudius')
        self.world.addAgent(self.claudius)
        self.world.setOrder(['Claudius'])

    def addStates(self):
        #define states
        self.world.defineState(None,'round',int)
        self.world.setState(None,'round',0)
        
        self.world.defineState(None,'poisoned',bool)
        self.world.setState(None,'poisoned',False)
                    
    def addTermination(self):
        #terminate if maxRounds reached
        self.world.addTermination(makeTree({'if': thresholdRow(stateKey(None,'round'),self.maxRounds),
                                   True: True, False: False}))

    def addActions(self):
        #add actions and appropriate dynamics
        action = self.claudius.addAction({'verb': 'poisons'})
        tree = makeTree(setTrueMatrix(stateKey(None,'poisoned')))
        self.world.setDynamics('poisoned',action,tree)
        tree = makeTree(incrementMatrix(stateKey(None,'round'),1))
        self.world.setDynamics('round',action,tree)     
        action =  self.claudius.addAction({'verb': 'do nothing'})
        self.world.setDynamics('round',action,tree) 
        
    def setModelAndRewards(self):
        #set models, rewards, and beliefs
        self.claudius.setReward(maximizeFeature(stateKey(None,'poisoned')), 1.0, True)
        
        self.world.setModel('Claudius', True)
                                
        key = stateKey(None,'poisoned')
        self.claudius.setBelief(key,Distribution({0: 0.5, 1: 0.5}),True)
        
    def testSetup(self):
        self.addStates()
        self.addTermination()
        self.addActions()
        self.setModelAndRewards()

    def testRun(self):
        self.testSetup()
        self.world.printState(beliefs=True)
        self.world.printModels()
        for t in range(self.maxRounds + 1):
            self.world.explain(self.world.step(),level=4)
            self.world.printState(beliefs=True)
            self.world.printModels()
            if self.world.terminated():
                break 

if __name__ == "__main__":
    suite = unittest.TestSuite()
    for method in dir(PoisonTestCase):
       if method.startswith("test"):
          suite.addTest(PoisonTestCase(method))
    unittest.TextTestRunner().run(suite)
            